import java.util.Arrays;

public class PriorityQueue {
    int[] elem;
    int usedSize = 0;

    public PriorityQueue(int[] elem) {
        this.elem = elem;
    }

    public void createHeap(int[] array) {
        for (int parent = (array.length-1-1)/2; parent >= 0; parent--) {
            shiftDown(array[parent],array.length);
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int child = root*2+1;
        while(child < len) {
            if(child+1 < len && elem[child] < elem[child+1]) {
                child++;
            }
            if(elem[root] < elem[child]) {
                swap(root,child);
                root = child;
                child = root*2 + 1;
            }else {
                break;
            }
        }
    }
    private void swap(int root,int child) {
        int tmp = elem[root];
        elem[root = elem[child];
        elem[child] = tmp;
    }

    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,elem.length*2);
        }
        usedSize++;
        elem[usedSize] = val;
        shiftUp(usedSize);
    }

    private void shiftUp(int child) {
        int parent = (child-1-1)/2;
        while(parent >= 0) {
//            if(child+1 < usedSize && elem[child] < elem[child+1]) {
//                child++;
//            }
            if(elem[parent] < elem[child]) {
                swap(parent,child);
                child = parent;
                parent = (child-1)/2;
            }else {
                break;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        swap(0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(isEmpty()) {
            return -1;
        }
        return elem[0];
    }
    public class Test {
        int[] elem = {1,6,8,4,23,677,4,32,8,9}
        PriorityQueue priorityQueue = new PriorityQueue(elem);

    }
}
